import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const projectId = searchParams.get('projectId')
    const status = searchParams.get('status')

    const where: any = {}
    if (projectId) where.projectId = projectId
    if (status) where.status = status

    const boms = await db.bOM.findMany({
      where,
      include: {
        project: {
          select: { id: true, name: true, key: true }
        },
        creator: {
          select: { id: true, name: true, username: true }
        },
        items: {
          include: {
            supplier: {
              select: { id: true, name: true, code: true }
            }
          }
        },
        hardwareVersions: {
          select: { id: true, version: true, name: true }
        },
        requirements: {
          select: { id: true, title: true, status: true }
        },
        _count: {
          select: {
            items: true,
            hardwareVersions: true,
            requirements: true
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    })

    return NextResponse.json(boms)
  } catch (error) {
    console.error('Error fetching BOMs:', error)
    return NextResponse.json(
      { error: 'Failed to fetch BOMs' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const {
      projectId,
      version,
      name,
      description,
      status,
      currency,
      creatorId
    } = body

    if (!projectId || !version || !name || !creatorId) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      )
    }

    const bom = await db.bOM.create({
      data: {
        projectId,
        version,
        name,
        description,
        status: status || 'DRAFT',
        currency: currency || 'CNY',
        creatorId
      },
      include: {
        project: {
          select: { id: true, name: true, key: true }
        },
        creator: {
          select: { id: true, name: true, username: true }
        }
      }
    })

    return NextResponse.json(bom, { status: 201 })
  } catch (error) {
    console.error('Error creating BOM:', error)
    return NextResponse.json(
      { error: 'Failed to create BOM' },
      { status: 500 }
    )
  }
}